let titles = [];
let cuoti = [];
let correctCount = 0;
const app = getApp();
let wrongQuestions = [];
let startTime;
let timer;
let totalQuestionTime = 0;

Page({
  data: {
    percent: 0,
    total: 0,
    isSelect: false,
    subject: null,
    userSelect: [],
    userScore: 0,
    totalScore: -1,
    totalError: 0,
    current: 1,
    correctAnswer: '',
    explain: '',
    currentTime: 0, // 新增变量来记录用户在当前页面的时间
    showFinishButton: false,
    answered: []
  },

  onLoad() {
    wx.cloud.database().collection('timu')
      .where({
        type: "多选"
      })
      .get()
      .then(res => {
        console.log('题库数据', res);
        let allTitles = res.data;

        let shuffledTitles = allTitles.sort(() => Math.random() - 0.5);
        titles = shuffledTitles.slice(0, 10);

        titles.forEach((item, index) => {
          item.serialNumber = index + 1;
        });
        this.setData({
          subject: titles[0],
          total: titles.length,
          answered: new Array(titles.length).fill(false)
        });
        startTime = Date.now();
        this.startTimer();
      });
  },

  startTimer() {
    timer = setInterval(() => {
      let currentTime = Math.floor((Date.now() - startTime) / 1000);
      this.setData({
        currentTime: currentTime // 更新用户在当前页面的时间
      });
    }, 1000);
  },

  optionChange(e) {
    let value = e.detail.value;
    this.setData({
      userSelect: value
    });
  },

  submitAnswer() {
    let currentNum = this.data.current - 1;
    if (!this.data.userSelect.length) {
      wx.showToast({
        icon: 'none',
        title: '请选择答案',
      });
      return;
    }

    this.setData({
      answered: this.data.answered.map((v, index) => index === currentNum ? true : v)
    });

    let that = this;
    wx.cloud.database().collection('timu').where({
      type: "多选",
      _id: this.data.subject._id
    }).get().then(res => {
      if (res.data.length > 0) {
        let explainData = res.data[0].explain;
        let correctAnswer = res.data[0].answer;
        that.setData({
          correctAnswer,
          explain: explainData
        });

        let options = that.data.subject.options;

        for (let code of that.data.userSelect) {
          let option = options.find(o => o.code === code);
          if (option) {
            option.color = that.data.userSelect.sort().toString() === correctAnswer.sort().toString() ? '#32CD32' : 'red';
          }
        }

        for (let i = 0; i < options.length; i++) {
          if (!that.data.userSelect.includes(options[i].code)) {
            if (options[i].code === res.data[0].answer) {
              options[i].color = '#32CD32';
            } else {
              options[i].color = 'black';
            }
          }
        }

        that.setData({
          subject: {
            ...that.data.subject,
            options
          }
        });

        let score = that.data.userSelect.sort().toString() === correctAnswer.sort().toString() ? 1 : 0;
        that.setData({
          userScore: that.data.userScore + score,
          totalScore: that.data.userScore + score
        });

        if (score === 1) {
          correctCount++;
        }

        if (score === 0) {
          that.saveCuotiToDatabase(res.data[0], that.data.userSelect);
        }

        if (currentNum === titles.length - 1) {
          that.setData({
            totalScore: that.data.userScore,
            totalError: cuoti.length,
            showFinishButton: true
          });
        }
      }
    });
  },

  saveCuotiToDatabase(questionData, userAnswer) {
    const openid = wx.getStorageSync('openid');
    const db = wx.cloud.database();
    const usersCollection = db.collection('users');

    usersCollection.where({
      openid: openid
    }).get().then(res => {
      if (res.data.length > 0) {
        let cuoti = res.data[0].cuoti || [];
        let existingQuestion = cuoti.find(item => item._id === questionData._id);
        if (existingQuestion) {
          console.log('已存在相同题目ID的记录', existingQuestion);
          wx.showToast({
            title: '此题目已记录为错题',
            icon: 'none'
          });
        } else {
          cuoti.push({
            _id: questionData._id,
            title: questionData.title,
            userAnswer: userAnswer,
            options: this.data.subject.options,
            correctAnswer: questionData.answer,
            type: questionData.type,
            explain: questionData.explain,
            timestamp: new Date().toISOString()
          });
          usersCollection.doc(res.data[0]._id).update({
            data: {
              cuoti: cuoti
            },
            success: res => {
              console.log('错题已成功保存到用户记录', res);
              wx.showToast({
                title: '错题记录成功',
                icon: 'success'
              });
            },
            fail: err => {
              console.error('保存错题失败', err);
              wx.showToast({
                title: '错题记录失败',
                icon: 'none'
              });
            }
          });
        }
      } else {
        console.error('用户记录不存在');
        wx.showToast({
          title: '用户记录不存在',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('查询用户记录失败', err);
    });
  },
  prevQuestion() {
    let currentNum = this.data.current;
    if (currentNum > 1) {
      currentNum--;
      let subject = titles[currentNum - 1];

      this.setData({
        current: currentNum,
        subject,
        userSelect: [],
        isSelect: false,
        correctAnswer: subject.answer,
        explain: subject.explain
      });
    } else {
      wx.showToast({
        icon: 'none',
        title: '已经是第一题了',
      });
    }
  },

  nextQuestion() {
    let currentNum = this.data.current;
    if (currentNum < titles.length) {
      if (!this.data.userSelect.length && !this.data.answered[currentNum - 1]) {
        wx.showToast({
          icon: 'none',
          title: '请先选择答案并提交，再进入下一题',
        });
        return;
      }
      currentNum++;
      let subject = titles[currentNum - 1];
      this.setData({
        current: currentNum,
        subject
      }, () => {
        if (this.data.answered[currentNum - 1]) {
          let that = this;
          wx.cloud.database().collection('timu').where({
            type: "多选",
            _id: subject._id
          }).get().then(res => {
            if (res.data.length > 0) {
              let explainData = res.data[0].explain;
              let correctAnswer = res.data[0].answer;
              that.setData({
                correctAnswer,
                explain: explainData
              });
            }
          });
        } else {
          this.setData({
            correctAnswer: '',
            explain: ''
          });
        }
        this.setData({
          userSelect: [],
          isSelect: false,
          currentQuestionTime: ''
        });
      });
    } else {
      wx.showToast({
        icon: 'static',
        title: '已经是最后一题了',
      });
    }
  },

  goToFinishPage() {
    if (timer) {
      clearInterval(timer);
      let totalQuestionTime = this.data.currentTime; // 使用 currentTime 作为总时间
      console.log('准备传递给answer-finish页面的答题总时间和答对题目数量：', totalQuestionTime, correctCount);
      wx.redirectTo({
        url: `/pages/answer-finish/answer-finish?totalTime=${totalQuestionTime}&correctCount=${correctCount}`,
      });
    }
  },

  // 收藏题目
  collectQuestion() {
    const questionData = {
      questionId: this.data.current,
      title: this.data.subject.title,
      options: this.data.subject.options,
      userAnswer: this.data.userSelect,
      correctAnswer: this.data.subject.answer,
      type: this.data.subject.type,
      explain: this.data.subject.explain,
      timestamp: new Date().toISOString()
    };

    const openid = wx.getStorageSync('openid');
    const db = wx.cloud.database();
    const usersCollection = db.collection('users');

    usersCollection.where({
      openid: openid
    }).get().then(res => {
      let save = res.data.save || [];
      let existingQuestion = save.find(item => item.title === questionData.title);
      if (existingQuestion) {
        console.log('已存在相同标题的记录', existingQuestion);
        wx.showToast({
          title: '此题目已收藏',
          icon: 'none'
        });
      } else {
        save.push(questionData);
        usersCollection.where({
          openid: openid
        }).update({
          data: {
            save: db.command.push(save)
          },
          success: res => {
            console.log('题目已成功保存到用户记录', res);
            wx.showToast({
              title: '收藏成功',
              icon: 'success'
            });
          },
          fail: err => {
            console.error('保存题目失败', err);
            wx.showToast({
              title: '收藏失败',
              icon: 'none'
            });
          }
        });
      }
    }).catch(err => {
      console.error('查询用户记录失败', err);
    });
  }
});